<?php

namespace app\api\behavior;
use think\Db;
use app\common\library\Token;
use think\facade\Response;

class ApiLog extends Response
{
    public function run($response)
    {
        if (request()->isPost())
        {	
            $user_id = 0;
        	$request_arr = request()->param();
        	if(isset($request_arr['token'])){
        		$data = Token::get($request_arr['token']);
        		$user_id = isset($data['user_id'])? $data['user_id'] : 0;
        	}else{
        		//登录
                if(isset($request_arr['account']) && $request_arr['account']){
                    $rs = Db::name('user')->where('username', $request_arr['account'])->find();
                    $user_id = isset($rs['id'])?$rs['id']:0;
                }
        	}

        	$content = $response->getContent(); //太长，需要截取 text长度65,535
            $content = substr($content, 0, 65531); //3的倍数
            // return true;
	        $data = array(
	        	'user_id'   => $user_id,
	            'param'     => request()->getInput(),
	            'source'   => isset($request_arr['terminal']) ? $request_arr['terminal'] : '',
	            'result'   => !is_scalar($content) ? json_encode($content) : $content,
	            'url'       => request()->url(),
	            'useragent' => request()->server('HTTP_USER_AGENT'),
	            'ip'        => request()->ip(),
	            'createtime'=>time(),
	        );
	        Db::name('api_log')->insert($data);
        }
    }

}
